<template>
  <div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-4xl mx-auto px-4">
      <div v-if="loading" class="text-center text-gray-500">加载中…</div>

      <div v-else class="bg-white shadow-lg rounded-xl overflow-hidden">
        <div class="md:flex">
          <div class="md:w-1/3 bg-white flex items-center justify-center p-6">
            <img v-if="product.image_base64" :src="imgSrc(product.image_base64)" alt="商品图片" @error="onImgError" class="w-full h-64 object-contain rounded-md" />
          </div>

          <div class="md:w-2/3 p-6">
            <h1 class="text-2xl font-semibold text-gray-800">{{ product.product_name }}</h1>
            <div class="text-sm text-gray-500 mt-2">库存: <strong class="text-gray-700">{{ product.stock || 1 }}</strong></div>
            <div class="mt-4 text-xl font-bold text-red-500">¥{{ product.price }}</div>

            <div class="mt-5 grid gap-3 grid-cols-1 sm:grid-cols-2">
              <div>
                <label class="block text-sm text-gray-600">邮箱（必填）</label>
                <input v-model="email" type="email" placeholder="请输入邮箱（订单回执）" required class="mt-1 block w-full border border-gray-200 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-200" />
              </div>

              <div>
                <label class="block text-sm text-gray-600">购买数量</label>
                <div class="mt-1">
                  <!-- 固定数量为 1，禁止修改 -->
                  <input type="number" value="1" disabled class="w-20 text-center border border-gray-200 rounded-md px-2 py-1 bg-gray-50" />
                </div>
              </div>
            </div>

            <div class="mt-5">
              <label class="inline-flex items-center text-gray-700">
                <input type="radio" value="wxpay" v-model="payMethod" class="form-radio text-blue-600" />
                <span class="ml-2">微信支付</span>
              </label>
            </div>

            <div class="mt-6">
              <button @click="onBuy" :disabled="!isValidEmail(email)" class="px-5 py-2 bg-blue-600 text-white rounded-lg shadow hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed">下单</button>
            </div>
          </div>
        </div>

        <div class="p-6 border-t border-gray-100">
          <h3 class="text-lg font-medium text-gray-800 mb-3">商品描述</h3>
          <div class="prose max-w-none text-gray-700" v-html="product.detail"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from '#imports'
import { useHead } from '#imports'

const route = useRoute()
const router = useRouter()
const id = route.query.id || route.query.productId
const product = ref({})
const loading = ref(true)
const email = ref('')
// 购买数量固定为 1
const qty = ref(1)
const payMethod = ref('wxpay')

useHead({ title: '商品详情 - 八八小店' })

function renderImage(b64) {
  if (!b64) return ''
  if (b64.startsWith('data:')) return `<img src="${b64}" />`
  return `<img src="data:image/png;base64,${b64}" />`
}

function imgSrc(b64) {
  if (!b64) return ''
  if (b64.startsWith('data:')) return b64
  return `data:image/png;base64,${b64}`
}

function onImgError(e) {
  // 图片加载失败时不替换为 favicon.svg，直接隐藏图片元素以保留白色占位
  try { e.target.style.display = 'none' } catch (err) { }
}

async function load() {
  if (!id) return
  try {
  const res = await fetch(`/api/product?id=${encodeURIComponent(id)}`)
    const json = await res.json()
    product.value = json.data || {}
  } catch (e) { console.error(e) }
  loading.value = false
}

function onBuy() {
  // Navigate to pay page - pay.vue will create the order using out_trade_no
  // pass return_url to our result page so pay.vue will callback there
  const params = new URLSearchParams()
  params.append('money', String(product.value.price || 0))
  params.append('name', product.value.product_name || '')
  params.append('product_id', String(product.value.id))
  params.append('type', payMethod.value || 'wxpay')
  params.append('qty', String(qty.value || 1))
  // Note: email is captured locally but not submitted to backend here per request
  // 邮箱现在为必填，传递到 pay 页面
  params.append('email', String(email.value || '').trim())
  params.append('return_url', `/shop/result`)
  const url = `/shop/pay?${params.toString()}`
  router.push(url)
}

function isValidEmail(v) {
  if (!v) return false
  return /\S+@\S+\.\S+/.test(String(v))
}

// 不再提供增减操作，数量固定为 1

onMounted(load)
</script>

<style scoped>
.product-page{ padding:20px; background: #fafafa; min-height:60vh }
.product-container{ max-width:980px; margin:0 auto; }
.card{ display:flex; gap:20px; background:#fff; border:1px solid #e8e8e8; border-radius:10px; padding:18px; box-shadow:0 6px 18px rgba(20,20,20,0.06); align-items:flex-start }
.left{ flex:0 0 280px }
.image{ width:100%; height:220px; border-radius:8px; overflow:hidden; background:linear-gradient(180deg,#fff,#f7f9fb); display:flex; align-items:center; justify-content:center; border:1px solid #f0f0f0 }
.image img{ width:100%; height:100%; object-fit:contain; display:block }
.right{ flex:1 }
.title{ margin:0 0 8px 0; font-size:20px; color:#1f2937 }
.meta{ color:#6b7280; margin-bottom:6px }
.price{ font-size:18px; margin:8px 0 }
.price .amount{ color:#ef4444; font-weight:600; }
.field{ margin:10px 0; display:flex; align-items:center; gap:10px }
.field label{ min-width:56px; color:#374151 }
.field input[type="email"], .field input[type="number"]{ padding:8px 10px; border:1px solid #e5e7eb; border-radius:6px; min-width:180px }
.qty-controls{ display:flex; align-items:center; gap:8px }
.qty-controls .small{ padding:4px 10px; border-radius:6px; border:1px solid #d1d5db; background:#fff }
.buy-row{ margin-top:14px }
.buy{ background:#2563EB; color:#fff; border:none; padding:8px 16px; border-radius:8px; cursor:pointer }
.buy:hover{ background:#1e40af }
.detail-section{ margin-top:18px }
.detail-section .detail{ background:#fff; border:1px solid #eee; padding:12px; border-radius:6px; color:#374151 }

/* small screens */
@media (max-width:720px){
  .card{ flex-direction:column }
  .left{ flex:0 0 auto }
  .image{ height:180px }
}
</style>
